package com.cloud.spring.demo.service;

import com.cloud.spring.demo.entity.User;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Log4j2
@Service
public class UserService {
    @Autowired
    User user;

    /**
     * 新增数据时,把findList缓存清理掉
     *
     * @param user
     * @return
     */
    @CacheEvict(cacheNames = "user", key = "findUserList")
    public User insert(User user) {
        return user;
    }

    /**
     * 删除数据时,把findList缓存清理掉,把user,user2中相同key(id)的缓存清理掉
     *
     * @param user
     * @return
     */
    @Caching(evict = {@CacheEvict(cacheNames = "user", key = "findList"), @CacheEvict(cacheNames = {"user", "user2"}, key = "#p0")})
    public User delete(User user) {
        return user;
    }

    /**
     * 清空user里的所有缓存
     */
    @CacheEvict(cacheNames = "user", allEntries = true)
    public void clearUser1All() {
        log.info("clearAll");
    }

    /**
     * 更新缓存数据时,把user,user2里相同key(id)的缓存替换掉,删除findList缓存
     *
     * @param user
     * @return
     */
    @CachePut(cacheNames = {"user", "user2"}, key = "#user.id")
    @CacheEvict(cacheNames = "user",key = "findList")
    public User update(User user) {
        return user;
    }

    /**
     * 查询操作时,将user同时保存到缓存user,user2中
     *
     * @param id
     * @return
     */
    @Cacheable(cacheNames = {"user", "user2"}, key = "#id", sync = true)
    public User findUser(int id) {
        log.info("本次请求没有走缓存");
        user.setId(id);
        return user;
    }

    /**
     * 将所有数据列表添加到findList缓存中
     *
     * @return
     */
    @Cacheable(cacheNames = "user", key = "findUserList", sync = true)
    public List<User> findUserList() {
        List<User> userList = new ArrayList<>();
        userList.add(user);
        userList.add(user);
        log.info("findUserList: 本次请求没有走缓存");
        return userList;
    }
}
